package com.wb3.meta.filter;

import com.wb3.meta.auth.JwtUtil;
import com.wb3.meta.config.AuthProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {
    private static final String AUTHORIZE_TOKEN = "token";

    private final AuthProperties authProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.debug("请求路径：{}",path);
        //如果未开启网关验证，则直接放行
        if (!authProperties.getEnable()) {
            log.debug("未开启网关验证，放行");
            return chain.filter(exchange);
        }
        path = replacePrefix(path); //移除固定前缀路径
        String requestUrl = request.getURI().getRawPath();
        //请求路径在忽略列表里，直接跳过
        if (ignore(path) || ignore(requestUrl)) {
            log.debug("请求url在忽略列表，放行");
            return chain.filter(exchange);
        }
        //2. 获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3. 获取请求头
        HttpHeaders headers = request.getHeaders();
        //4. 请求头中获取令牌
        String token = headers.getFirst(AUTHORIZE_TOKEN);


        //5. 判断请求头中是否有令牌
        if (StringUtils.isEmpty(token)) {
            //6. 响应中放入返回的状态吗, 没有权限访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //7. 返回
            return response.setComplete();
        }

        //8. 如果请求头中有令牌则解析令牌
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //9. 解析jwt令牌出错, 说明令牌过期或者伪造等不合法情况出现
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //10. 返回
            return response.setComplete();
        }
        //11. 放行
        return chain.filter(exchange);
    }

    /**
     * 检查是否忽略url
     * @param path 路径
     * @return boolean
     */
    private boolean ignore(String path) {
        return authProperties.getIgnoreUrl().stream()
                .map(url -> url.replace("/**", ""))
                .anyMatch(path::startsWith);
    }
    /**
     * 移除模块前缀
     * @param path 路径
     * @return String
     */
    private String replacePrefix(String path) {
        if (path.startsWith("/meta")) {
            return path.substring(path.indexOf("/",1));
        }
        return path;
    }

    //order越小，过滤器越提前处理
    @Override
    public int getOrder() {
        return -100;
    }
}
